package com.gjm.demo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.gjm.demo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {

        response.setContentType("image/jpeg");

        //一般情况下, 这个处理是前端做的,清除缓存
        response.setHeader("Progma", "No-cahce");

        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());

        //验证码使用期需要有时间限制，超过时间即验证失败
        //使用session验证码开始使用的时间
        session.setAttribute(captchaProperties.getSession().getDate(), System.currentTimeMillis());

        //使用session保存验证码内容
        session.setAttribute(captchaProperties.getSession().getCaptchaCode(), lineCaptcha.getCode());

        //将验证码写出到浏览器
        lineCaptcha.write(response.getOutputStream());
    }

    @RequestMapping("/check")
    public boolean check(String codeHtml, HttpSession session) {
        if (!StringUtils.hasLength(codeHtml)) {
            return false;
        }

        //获取当前时间
        long now = System.currentTimeMillis();

        //需要验证码内容相同并且没有超过有效时间
        if (codeHtml.equalsIgnoreCase((String)session.getAttribute(captchaProperties.getSession().getCaptchaCode())) &&
            now - (long)session.getAttribute(captchaProperties.getSession().getDate()) <= captchaProperties.getDate()) {
            return true;
        }

        return false;
    }
}
